package com.netty.pro.netty.nio;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xuzn
 * @ClassName: UseMappedByteBuffer
 * @ProjectName echo-project
 * @date 2020/3/5/11:56
 */
public class UseMappedByteBuffer {

  /**
   * MappedByteBuffer可以让文件直接在内存(堆外内存)修改,操作系统不需要拷贝一次
   *
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt", "rw");
    // 获取channel
    FileChannel accessFileChannel = randomAccessFile.getChannel();
    /**
     * 参数1:使用的是读写模式
     * 参数2:起始位置
     * 参数3:代表映射到内存的大小(即能在内存中存多少1.txt文件信息)
     * 可以修改的范围是0~5,不包含6
     * MappedByteBuffer实际类型是DirectByteBuffer
     */
    MappedByteBuffer mappedByteBuffer = accessFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 6);
    mappedByteBuffer.put(0, (byte) 'H');
    mappedByteBuffer.put(5, (byte) ';');
    randomAccessFile.close();
    System.out.println("修改成功了~~");
  }
}
